#!/bin/bash
root=${1:-./}

# 先建映射（同你已有脚本）
declare -A MODEL_MAP
while read -r node model sn; do
    MODEL_MAP[$node]="$model ${sn: -7}"
done < <(nvme list | awk '/^\/dev\/nvme[0-9]/ {print $1,$4,$2}')

# 参数：fio 结果文件
get_lat_usec() {
    awk '
    /^[[:space:]]*lat \(nsec\):/ { for(i=1;i<=NF;i++) if($i~"avg=") {gsub(/avg=|,/,"",$i); print $i/1000; exit} }
    /^[[:space:]]*lat \(usec\):/ { for(i=1;i<=NF;i++) if($i~"avg=") {gsub(/avg=|,/,"",$i); print $i;   exit} }
    /^[[:space:]]*lat \(msec\):/ { for(i=1;i<=NF;i++) if($i~"avg=") {gsub(/avg=|,/,"",$i); print $i*1000; exit} }
    ' "$1"
}

# 输出 Excel 可直接识别的 TSV 表头（制表符分隔）
{ printf "Disk\tModel_SN\tSeqRead_MB/s\tSeqWrite_MB/s\tReadLat_usec\tWriteLat_usec\tRandRead_IOPS\tRandWrite_IOPS\tRandReadLat_usec\tRandWriteLat_usec\n"

for disk in "$root"/nvme*n1; do
    [[ -d $disk ]] || continue
    d=$(basename "$disk")
    model_sn="${MODEL_MAP[/dev/$d]:-N/A}"
    show_name="$d (${MODEL_MAP[/dev/$d]:-N/A})"

    # 下面所有字段取法同你原脚本，这里只留关键行
    sr=$(sed -n 's/.*bw=[0-9.]\+MiB\/s (\([0-9.]\+\)MB\/s).*/\1/p' "$disk"/SeqRead_128K_QD128.out | tail -1)
    sw=$(sed -n 's/.*bw=[0-9.]\+MiB\/s (\([0-9.]\+\)MB\/s).*/\1/p' "$disk"/SeqWrite_128K_QD128.out | tail -1)
    #[[ -z $sr ]] && sr=$(sed -n 's/.*bw=[0-9.]\+MiB\/s (\([0-9.]\+\)MB\/s).*/\1/p' "$disk"/SeqRead_128K_QD128.out | tail -1)
    #[[ -z $sw ]] && sw=$(sed -n 's/.*bw=[0-9.]\+MiB\/s (\([0-9.]\+\)MB\/s).*/\1/p' "$disk"/SeqWrite_128K_QD128.out | tail -1)

    #rl=$(awk '/clat.*avg=/{for(i=1;i<=NF;i++) if($i~"avg=") {sub(/avg=/,"",$i); sub(/,$/,"",$i); print $i; exit}}' "$disk"/SeqReadLatency_128K_QD1.out)
    #wl=$(awk '/clat.*avg=/{for(i=1;i<=NF;i++) if($i~"avg=") {sub(/avg=/,"",$i); sub(/,$/,"",$i); print $i; exit}}' "$disk"/SeqWriteLatency_128K_QD1.out)

    riops=$(sed -n 's/.*read: IOPS=\([0-9]\+\(k\)\{0,1\}\).*/\1/p' "$disk"/RandRead_4K_QD32.out | tail -1)
    wiops=$(sed -n 's/.*write: IOPS=\([0-9]\+\(k\)\{0,1\}\).*/\1/p' "$disk"/RandWrite_4K_QD32.out | tail -1)

    #rrlat=$(awk '/clat.*avg=/{for(i=1;i<=NF;i++) if($i~"avg=") {sub(/avg=/,"",$i); sub(/,$/,"",$i); print $i; exit}}' "$disk"/RandReadLatency_4K_QD1.out)
    #rwlat=$(awk '/clat.*avg=/{for(i=1;i<=NF;i++) if($i~"avg=") {sub(/avg=/,"",$i); sub(/,$/,"",$i); print $i; exit}}' "$disk"/RandWriteLatency_4K_QD1.out)
    rl=$(get_lat_usec "$disk"/SeqReadLatency_128K_QD1.out)
    wl=$(get_lat_usec "$disk"/SeqWriteLatency_128K_QD1.out)
    rrlat=$(get_lat_usec "$disk"/RandReadLatency_4K_QD1.out)
    rwlat=$(get_lat_usec "$disk"/RandWriteLatency_4K_QD1.out)
    # 兜底
    sr=${sr:-N/A}; sw=${sw:-N/A}; rl=${rl:-N/A}; wl=${wl:-N/A}
    riops=${riops:-N/A}; wiops=${wiops:-N/A}; rrlat=${rrlat:-N/A}; rwlat=${rwlat:-N/A}

    # 关键：用制表符 \t 分隔，末尾直接换行
     printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" \
           "$d" "$model_sn" "$sr" "$sw" "$rl" "$wl" "$riops" "$wiops" "$rrlat" "$rwlat"
done 
} | tee result.tsv 
